# encoding:utf-8

import requests
import base64

'''
通用文字识别
'''

def general_ocr_recognition(image_path, user_config):
    # 获取access_token
    CLIENT_ID = user_config["baidu_ocr"]["client_id"]
    CLIENT_SECRET = user_config["baidu_ocr"]["client_secret"]
    TOKEN_URL = user_config["baidu_ocr"]["token_url"]

    # 构建请求 URL
    url = f"{TOKEN_URL}?grant_type=client_credentials&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}"

    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    # 发起请求获取 access_token
    response = requests.request("POST", url, headers=headers, data=payload)

    # 解析响应获取 access_token
    access_token = response.json()["access_token"]

    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    # 二进制方式打开图片文件
    with open(image_path, 'rb') as f:
        img = base64.b64encode(f.read())

    params = {"image": img}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        return response.json()
    return None